<template>
  <div id="vditor"/>
</template>

<script setup lang="ts">
import {ref, onMounted, watch} from 'vue';
import Vditor from 'vditor';
import 'vditor/dist/index.css';
import {storeToRefs} from "pinia";
import {useAppStore} from "@/store/module/app";
import {uploadFile, linkToImg} from '~/settings'


const {theme} = storeToRefs(useAppStore())
const vditor = ref<Vditor | null>(null);
const props = defineProps({
  content: {
    type: String,
    default: ''
  }
})
const emits = defineEmits(['update:content', 'renderFinish'])


onMounted(() => {
  vditor.value = new Vditor('vditor', {
    theme: 'classic',
    minHeight: 2000,
    after: () => {
      vditor.value!.setValue(props.content);
      setTimeout(() => {
        vditor.value!.setValue(props.content);
      }, 50)
      if (theme.value === 'dark') {
        vditor.value!.setTheme('dark', 'dark', 'solarized-dark256')
      } else if (theme.value === 'light') {
        vditor.value!.setTheme('classic', 'light', 'ant-design')
      }
      emits('renderFinish')
    },
    input: (value) => {
      emits('update:content', value)
    },
    toolbarConfig: {
      pin: true,  //是否固定工具栏
      hide: false  //是否隐藏工具栏
    },
    counter: {
      enable: true,
      type: "text",
    },
    outline: {
      enable: true,
      position: 'left',
    },
    toolbar: [
      'outline', 'undo', 'redo', '|',
      'emoji', 'headings', 'bold', 'italic', 'strike', '|',
      'line', 'quote', 'list', 'ordered-list', 'check', 'outdent', 'indent', 'code', 'inline-code', 'insert-after', 'insert-before', '|',
      'code-theme', 'content-theme', '|',
      'upload', 'link', 'table', 'edit-mode', 'both', 'export'],
    upload: {
      url: uploadFile.url,
      fieldName: uploadFile.name,
      multiple: false,
      format: (_: any, responseText: string) => {
        let res = JSON.parse(responseText)

        let name = res.data.split('/').pop();
        if (res.code !== 0) {
          return JSON.stringify({
            msg: res.msg,
            code: res.code,
            data: {
              errFiles: [name],
            }
          })
        }
        return JSON.stringify({
          msg: res.msg,
          code: res.code,
          data: {
            succMap: {
              [name]: res.data
            }
          }
        })
      },
      linkToImgUrl: linkToImg.url,
    }
  });
});


watch(theme, () => {
  if (theme.value === 'dark') {
    vditor.value!.setTheme('dark', 'dark', 'solarized-dark256')
  } else if (theme.value === 'light') {
    vditor.value!.setTheme('classic', 'light', 'ant-design')
  }
})

</script>

<style scoped>
:deep(.vditor-outline) {
  height: 75vh;
  position: sticky;
  top: 70px;
}
</style>